﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZXing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Dting;
using static User_manage.User_Lgon;

namespace Printing_interface
{
    [Serializable]
    public partial class Printing_Interface : UserControl
    {
        public DataTable _PrintDataTable;
        public User_Print user_Print = new User_Print();
        Serialize_Class _Serialize_Class = new Serialize_Class();
        ini_Class _ini_Class = new ini_Class("Config\\sys_data.ini");
        int now_count = 0;

        public List<Barcod_data> barcod_Data = new List<Barcod_data>();

        public string now_printName = "";//当前使用
        public string isName = "";//当前被选定的类
       

        //打印信息图片
        public Image Print_Image = null;

        //权限
        public H_Level User_Level;

        public Printing_Interface()
        {
            InitializeComponent();
            SetStyle(ControlStyles.ResizeRedraw | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
            UpdateStyles();

            printing_editingBas1._add_click += Printing_editingBas1__add_click;
            printing_editingBas1._delete_click += Printing_editingBas1__delete_click;

            init_devertice();
            init_data();

            //读取设备数据
            print_read();
            ;
        }


        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;
                //cp.Style &= ~0x02000000;
                return cp;
            }
        }

        //权限切换
        public void User_sw()
        {
            print_read();

            switch (User_Level)
            {
                case H_Level.None:
                    printing_editingBas1.ReadOnly = true;
                    groupBox3.Enabled = false;
                    break;

                case H_Level.管理员:
                    printing_editingBas1.ReadOnly = false;
                    groupBox3.Enabled = true;
                    break;
            }
        }

        string new_day = "0023-01-01";
        private void UserControl1_Load(object sender, EventArgs e)
        {
            ;
        }

        //计数清零
        private void button1_Click(object sender, EventArgs e)
        {
            now_count = 0;
        }

        //打印
        private void uiButton1_Click(object sender, EventArgs e)
        {
            if (User_Level == H_Level.生产员 || User_Level == H_Level.班组长 || User_Level == H_Level.管理员)
            {
                Print_Hand = true;
                Print(1, true);
            }
            else
            {
                MessageBox.Show("权限错误，请切换为生产员权限/或更高的管理员权限", "错误提示");
                return;
            }

        }
        //预览
        private void uiButton2_Click(object sender, EventArgs e)
        {
            Print_Hand = true;
            Print();
        }

        private void Printing_editingBas1__delete_click(object sender)
        {
            string[] buf = sender as string[];
            if (buf != null )
            {
                for (int i = 0; i < buf.Length; i++)
                {
                    var data_buf = barcod_Data.Find(x => x.Bar_name == buf[i] || x.Bar_name==null);
                    if (data_buf !=null)
                    {
                        int index = barcod_Data.IndexOf(data_buf);
                        barcod_Data.RemoveAt(index);
                    }
                }

                if (_Serialize_Class.Serialize(barcod_Data, Application.StartupPath + "\\Config\\PrintData.config") == 0)
                {
                    //MessageBox.Show("数据保存成功！", "提示");
                }
                else
                {
                    MessageBox.Show("数据保存失败！", "提示");
                }
            }
            ;
        }

        private void Printing_editingBas1__add_click(object sender)
        {
            isName = "";
            view_contorlClear();
            if (printing_editingBas1.ColumnCount >0 )
            {
                barcod_Data.Add(new Barcod_data(string.Empty));

                //添加一行后进入编辑状态
                printing_editingBas1.CurrentCell = printing_editingBas1.Rows[printing_editingBas1.RowCount-1].Cells[0];
                printing_editingBas1.BeginEdit(true);
            }
            ;
        }

        string str_buf = "";
        //编辑完成事件
        private void printing_editingBas1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {

            //判断IP是否符合要求
            //string str1 = printing_editingBas1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
            //try
            //{
            //    int.Parse(str1);
            //    printing_editingBas1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = str1;
            //}
            //catch
            //{
            //    printing_editingBas1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = str_buf;
            //    str_buf = "";
            //    return;
            //}

            print_save(e);
        }

        //编辑中事件
        private void printing_editingBas1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            DataGridViewTextBoxEditingControl editingControl = e.Control as DataGridViewTextBoxEditingControl;
            if (editingControl != null)
            {
                str_buf = editingControl.Text;
            }
        }

        //点击事件
        private void printing_editingBas1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            ;//groupBox2 isName

            DataGridView Grid = sender as DataGridView;
            if (Grid != null)
            {
                if (e.Button == MouseButtons.Right)
                {
                    ;
                }
                else
                {
                    if (e.RowIndex > -1 && e.ColumnIndex == -1)
                    {
                        string[] str = gridview_tobox(Grid, e.RowIndex, e.ColumnIndex);
                        if (str != null && str[0] != string.Empty)
                        {
                            isName = str[0];
                            //显示子类的数据
                            var buf = barcod_Data.Find(x => x.Bar_name == isName);
                            int index = barcod_Data.IndexOf(buf);
                            if (index >= 0)
                            {
                                view_contorldata(barcod_Data[index]);
                            }
                            groupBox2.Text = "条码信息-" + str[0];
                            ;
                        }
                        else
                        {
                            groupBox2.Text = "条码信息";
                        }
                    }
                }
            }

        }


        //点击输入框数据保存事件
        private void User_CheckedChanged(object sender, EventArgs e)
        {
            if (isName != string.Empty)
            {
                int vlave = 0;
                var buf = barcod_Data.Find(x => x.Bar_name == isName);
                int index = barcod_Data.IndexOf(buf);
                if (index >= 0)
                {
                    Barcod_data bar_buf = barcod_Data[index];
                    buf.line_state = checkBox1.Checked;
                    buf.line_name = textBox2.Text;
                    buf.timer_state = checkBox2.Checked;
                    buf.timer_Format = comboBox1.Text;
                    buf.produce_state = checkBox3.Checked;
                    buf.produce_sn = textBox4.Text;
                    buf.Incremental_state = checkBox4.Checked;
                    int.TryParse(textBox5.Text, out vlave);
                    buf.Incremental_sn = vlave;
                    buf.Incremental_Format = textBox6.Text;
                    buf._PrintDevice = com_PrintDevice.Text;
                    barcod_Data[index] = bar_buf;

                }
                if (_Serialize_Class.Serialize(barcod_Data, Application.StartupPath + "\\Config\\PrintData.config") == 0)
                {
                    //MessageBox.Show("数据保存成功！", "提示");
                }
                else
                {
                    MessageBox.Show("数据保存失败！", "提示");
                }


            }
           ;
        }

        private void com_PrintDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            //保存数据
            //_PrintDataTable = _Serialize_Class.GetDataGridView(printing_editingBas1);
            //_PrintDataTable.TableName = com_PrintDevice.Text;

            //if (_Serialize_Class.Serialize(_PrintDataTable, Application.StartupPath + "\\Config\\PrintData.config") == 0)
            //{
            //    //MessageBox.Show("数据保存成功！", "提示");
            //}
            //else
            //{
            //    MessageBox.Show("数据保存失败！", "提示");
            //}

        }

        //显示打印数据
        public void init_data()
        {
            //printing_editingBas1.Rows.Clear();
            //禁止排序
            //if (printing_editingBas1.Columns.Count > 0)
            //{
            //    for (int i = 0; i < printing_editingBas1.Columns.Count; i++)
            //    {
            //        printing_editingBas1.Columns[i].SortMode = DataGridViewColumnSortMode.Programmatic;
            //    }
            //}
        }

        public void init_devertice()
        {
            //搜索设备
            com_PrintDevice.Items.Clear();
            string[] _Printer = user_Print.GetPrinterDevice();
            if (_Printer != null)
            {
                for (int i = 0; i < _Printer.Length; i++)
                {
                    com_PrintDevice.Items.Add(_Printer[i]);
                }
            }
        }

        public int add_Column(DataGridView dataGridView, string[] Row_str)
        {
            try
            {
                DataGridViewRowCollection rows = dataGridView.Rows;
                rows.Add(Row_str);
            }
            catch { return 1; }
            return 0;
        }

        //开启软件
        public void init_dataSave()
        {
            //获取上次计数
            int.TryParse(_ini_Class.Read_Ini("sys_data", "now_count"), out now_count);
            //获取上一天的时间
            new_day = _ini_Class.Read_Ini("sys_data", "now_timerdate");
            //判断是否是新的一天
            int compNum = DateTime.Compare(DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")), DateTime.Parse(new_day));
            if (compNum > 0)
            {
                now_count = 0;
            }
        }


        //退出保存当前日期
        public void end_dataSave()
        {
            _ini_Class.Write_Ini("sys_data", "now_timerdate", DateTime.Now.ToString("yyyy-MM-dd"));
        }

        //打印
        public bool Print_Hand = false;
        public string Print_strint = "";
        string buf_device = "";
        public int Print(int _Copies=1, bool P_state = false)
        {
            Print_strint = "";
            buf_device = "";

            this.Invoke(new Action(() => {
                Print_strint = textBox1.Text;
                buf_device = com_PrintDevice.Text;
            }));

            if (Print_Hand && Print_strint == string.Empty)
            {
                MessageBox.Show("打印内容不能为空", "提示");
                return 1;
            }
            if (Print_Hand && buf_device == string.Empty)
            {
                MessageBox.Show("打印设备不能为空", "提示");
                return 2;
            }

            if (buf_device == string.Empty)
            {
                return 2;
            }

            //生成打印条码规则

            try
            {
                //
                int vlaue = 0;

                print_read2();
                Barcod_data bar_buf = barcod_Data.Find(x => x.Bar_name == now_printName);


                for (int i = 0; i < _Copies; i++)
                {
                    //生成打印条码规则
                    string line_sn = _ini_Class.Read_Ini("sys_data", "line_sn");
                    //是否累计
                    if (bar_buf.Incremental_state)
                    {
                        now_count++;
                    }
                    else
                    {
                        int.TryParse(bar_buf.produce_sn, out now_count);

                    }

                    //生产批次
                    if (bar_buf.produce_state)
                    {
                        Print_strint = bar_buf.line_name + DateTime.Now.Date.ToString(bar_buf.timer_Format) + now_count.ToString(bar_buf.Incremental_Format);
                    }
                    else
                    {
                        Print_strint = bar_buf.line_name + DateTime.Now.Date.ToString(bar_buf.timer_Format);
                    }
                    
                    _ini_Class.Write_Ini("sys_data", "now_count", now_count.ToString());


                    //是否为手动打印
                    if (Print_Hand)
                    {
                        this.Invoke(new Action(() =>
                        {
                            Print_strint = textBox1.Text;
                        }));
                    }


                    ;
                    int B_width = bar_buf.Bar_width;
                    int B_height = bar_buf.Bar_height;

                    int D_width = bar_buf.Bar_x;
                    int D_height = bar_buf.Bar_y;

                    Image _image = user_Print.Create_Barcode(Print_strint, B_width, B_height, 300, 300, BarcodeFormat.CODE_128);
                    Image _image1 = user_Print.GetContorlImage(_image, Print_strint);
                    pictureBox1.Image = (Image)_image1.Clone();

                    //开始打印
                    user_Print.Preview_state = P_state;
                    user_Print.buf_data = (Image)_image1.Clone();
                    Print_Image = (Image)_image1.Clone();
                    user_Print.info_x = D_width;
                    user_Print.info_y = D_height;
                    user_Print.Printer(300, 300, 1, buf_device);
                }
            }
            catch
            {
                return 3;
            }
            return 0;
        }




        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ///条码参数
        [Serializable]
        public class Barcod_data
        {
            public string Bar_name;     //条码名称
            public int Bar_width;       //条码宽
            public int Bar_height;      //条码高度
            public int Bar_x;           //条码X
            public int Bar_y;           //条码Y

            public bool line_state;     //线条名称是否开启
            public string line_name;    //线条名称

            public bool timer_state;    //时间是否开启
            public string timer_Format; //时间格式

            public bool produce_state;      //生产批次是否开启
            public string produce_sn;       //批次

            public bool Incremental_state;      //是否递增累计
            public int Incremental_sn;          //累计计数
            public string Incremental_Format;   //批次格式

            public string _PrintDevice;     //打印设备名称
            public Barcod_data()
            {; }

            public Barcod_data(string str)
            { 
                Bar_name =str;
                line_state = true;
                timer_state = true;
                produce_state = true;
                Incremental_state = true;
            }
        }

        //保存数据到文件
        public int print_save(DataGridViewCellEventArgs e)
        {
            //if (isName == string.Empty) return 4;

           
            string strmain = printing_editingBas1.Rows[e.RowIndex].Cells[0].FormattedValue.ToString();
            isName = strmain;
            //为空判断
            if (strmain == string.Empty)
            {
                MessageBox.Show("名称不能为空，请检查！", "提示");
                int a = e.RowIndex;
                try { printing_editingBas1.Rows.RemoveAt(a); } catch {; }
                return 2;
            }
            //判断是否有重复
            if (e.ColumnIndex==0 && barcod_Data != null )
            {
                string str = "";
                bool str_state = not_User(printing_editingBas1, strmain,ref str);
                if (!str_state)
                {
                    MessageBox.Show("有重复名称，请检查！", "提示");
                    printing_editingBas1.CurrentCell = printing_editingBas1.Rows[e.RowIndex].Cells[0];
                    printing_editingBas1.BeginEdit(true);
                    //try { printing_editingBas1.Rows.Remove(printing_editingBas1.Rows[e.RowIndex]); } catch {; }
                    return 3;
                }
            }


            try
            {

                //记录数据
                int vlave = 0;
                int index = e.RowIndex;
                if (index >= 0)
                {
                    Barcod_data bar_buf = barcod_Data[index];
                    bar_buf.Bar_name = (printing_editingBas1.Rows[e.RowIndex].Cells[0].Value != null) ? printing_editingBas1.Rows[e.RowIndex].Cells[0].Value.ToString() : "";
                    int.TryParse((printing_editingBas1.Rows[e.RowIndex].Cells[1].FormattedValue != null) ? printing_editingBas1.Rows[e.RowIndex].Cells[1].FormattedValue.ToString() : "0", out vlave);
                    bar_buf.Bar_width = vlave;
                    int.TryParse((printing_editingBas1.Rows[e.RowIndex].Cells[2].FormattedValue != null) ? printing_editingBas1.Rows[e.RowIndex].Cells[2].FormattedValue.ToString() : "0", out vlave);
                    bar_buf.Bar_height = vlave;
                    int.TryParse((printing_editingBas1.Rows[e.RowIndex].Cells[3].FormattedValue != null) ? printing_editingBas1.Rows[e.RowIndex].Cells[3].FormattedValue.ToString() : "0", out vlave);
                    bar_buf.Bar_x = vlave;
                    int.TryParse((printing_editingBas1.Rows[e.RowIndex].Cells[4].FormattedValue != null) ? printing_editingBas1.Rows[e.RowIndex].Cells[4].FormattedValue.ToString() : "0", out vlave);
                    bar_buf.Bar_y = vlave;
                    barcod_Data[index] = bar_buf;
                }

                //删除空行
                for (int i = 0; i < printing_editingBas1.RowCount; i++)
                {
                    string str = (printing_editingBas1.Rows[i].Cells[0].Value!=null)?printing_editingBas1.Rows[i].Cells[0].Value.ToString(): string.Empty;
                    if (str==string.Empty)
                    {
                        try { printing_editingBas1.Rows.RemoveAt(i); } catch {; }
                    }
                    str = barcod_Data[i].Bar_name;
                    if (str == string.Empty || str==null)
                    {
                        barcod_Data.RemoveAt(i);
                    }
                }

                //显示控件数据
                var buf = barcod_Data.Find(x => x.Bar_name == isName);
                index = barcod_Data.IndexOf(buf);
                if (index >= 0)
                {
                    view_contorldata(barcod_Data[index]);
                }
                groupBox2.Text = "条码信息-" + isName;
                ;

                if (_Serialize_Class.Serialize(barcod_Data, Application.StartupPath + "\\Config\\PrintData.config") == 0)
                {
                    //MessageBox.Show("数据保存成功！", "提示");
                }
                else
                {
                    MessageBox.Show("数据保存失败！", "提示");
                }

            }
            catch (Exception er)
            {
                return 1;
            }
            return 0;
        }

        //读取文件到数据
        public void print_read()
        {
            //获取打印名称
            now_printName = _ini_Class.Read_Ini("sys_data", "Print_name");
            label5.Text = "当前使用名称:" + now_printName;           
            List<Barcod_data> buf = _Serialize_Class.Deserialize<List<Barcod_data>>(Application.StartupPath + "\\Config\\PrintData.config");
            if (buf!=null)
            {
                barcod_Data = buf;
                view_data();

                var buf_m = barcod_Data.Find(x => x.Bar_name == now_printName);
                if (buf_m !=null)
                { com_PrintDevice.Text = buf_m._PrintDevice; }
            }
            ;
        }

        public void print_read2()
        {
            //获取打印名称
            now_printName = _ini_Class.Read_Ini("sys_data", "Print_name");
            label5.Text = "当前使用名称:" + now_printName;
            List<Barcod_data> buf = _Serialize_Class.Deserialize<List<Barcod_data>>(Application.StartupPath + "\\Config\\PrintData.config");
            if (buf != null)
            {
                barcod_Data = buf;
            }
    ;
        }


        //返回鼠标点击行的所有数据
        public string[] gridview_tobox(DataGridView dataGridView, int Rows, int columns)
        {
            string[] tabel_str = new string[dataGridView.Columns.Count];
            try
            {
                if (Rows > -1)
                {
                    for (int j = 0; j < (dataGridView.Columns.Count); j++)
                    {
                        tabel_str[j] = Convert.ToString(dataGridView.Rows[Rows].Cells[j].Value);

                    }
                    return tabel_str;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }

        }

        //判断不能重复用户名
        public Boolean not_User(DataGridView dt, string str, ref string id)
        {
            try
            {
                int a = 0;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string buf =(dt.Rows[i].Cells[0].Value !=null)? dt.Rows[i].Cells[0].Value.ToString():"";
                    if (str == buf)
                    { a++; if (a > 1) { id = str; return false; } }
                }
            }
            catch { return false; }
            return true;
        }

        //显示到表格
        public void view_data()
        {
            if (barcod_Data != null)
            {
                printing_editingBas1.Rows.Clear();
                for (int i = 0; i < barcod_Data.Count; i++)
                {
                    printing_editingBas1.Rows.Add();
                    printing_editingBas1.Rows[i].Cells[0].Value = barcod_Data[i].Bar_name;
                    printing_editingBas1.Rows[i].Cells[1].Value = barcod_Data[i].Bar_width.ToString();
                    printing_editingBas1.Rows[i].Cells[2].Value = barcod_Data[i].Bar_height.ToString();
                    printing_editingBas1.Rows[i].Cells[3].Value = barcod_Data[i].Bar_x.ToString();
                    printing_editingBas1.Rows[i].Cells[4].Value = barcod_Data[i].Bar_y.ToString();
                }
            }
        }

        //显示到控件
        public void view_contorldata(Barcod_data _barcod_Data)
        {

            checkBox1.Checked = _barcod_Data.line_state;
            textBox2.Text = _barcod_Data.line_name;
            checkBox2.Checked = _barcod_Data.timer_state;

            comboBox1.Text = _barcod_Data.timer_Format;
            textBox3.Text = DateTime.Now.Date.ToString(comboBox1.Text);

            checkBox3.Checked = _barcod_Data.produce_state;
            textBox4.Text = _barcod_Data.produce_sn;
            checkBox4.Checked = _barcod_Data.Incremental_state;


            textBox5.Text = _barcod_Data.Incremental_sn.ToString(textBox6.Text);
            //textBox6.Text = _barcod_Data.Incremental_Format;

            com_PrintDevice.Text = _barcod_Data._PrintDevice;

            //删除空行
            for (int i = 0; i < printing_editingBas1.RowCount; i++)
            {
                string str = (printing_editingBas1.Rows[i].Cells[0].Value != null) ? printing_editingBas1.Rows[i].Cells[0].Value.ToString() : string.Empty;
                if (str == string.Empty)
                {
                    try { printing_editingBas1.Rows.RemoveAt(i); } catch {; }
                }
                str = barcod_Data[i].Bar_name;
                if (str == string.Empty || str == null)
                {
                    barcod_Data.RemoveAt(i);
                }
            }
        }

        public void view_contorlClear()
        {
            checkBox1.Checked = true;
            textBox2.Text = "1";
            checkBox2.Checked = true;
            comboBox1.Text = "yyMMdd";
            textBox3.Text = DateTime.Now.Date.ToString(comboBox1.Text);
            checkBox3.Checked = true;
            textBox4.Text ="";
            checkBox4.Checked = true;
            textBox5.Text = "";
            textBox6.Text = "0000";

            com_PrintDevice.Text = "";
        }


    }
}